/**
 * @author:albert
 * @date:2016年7月6日
 */
package com.bkbw.live.database.util;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSourceFactory;

import com.bkbw.live.database.DatabaseMain;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.DataSources;

/**
 * @author albert
 *
 */
public class C3p0DatabasePool {
	private static DataSource dataSource;
	static {
		try {
//			InputStream in = DatabaseMain.class.getClassLoader().getResourceAsStream("jdbc.properties");
//			Properties jdbcProperties = new Properties();
//			jdbcProperties.load(in);
//			in = DatabaseMain.class.getClassLoader().getResourceAsStream("c3p0.properties");
//			Properties c3p0Properties = new Properties();
//			c3p0Properties.load(in);
//			DataSource unpooled = DataSources.unpooledDataSource(jdbcProperties.getProperty("url"), jdbcProperties);
//			
//			dataSource = DataSources.pooledDataSource(unpooled, c3p0Properties);
			
			//dataSource = new ComboPooledDataSource();
			
			InputStream in = DatabaseMain.class.getClassLoader().getResourceAsStream("jdbc.properties");
			Properties jdbcProperties = new Properties();
			jdbcProperties.load(in);
			in.close();
			in = DatabaseMain.class.getClassLoader().getResourceAsStream("c3p0.properties");
			Properties c3p0Properties = new Properties();
			c3p0Properties.load(in);
			in.close();

			ComboPooledDataSource cpds = new ComboPooledDataSource();
			cpds.setDriverClass(jdbcProperties.getProperty("driverClass"));
			cpds.setJdbcUrl(jdbcProperties.getProperty("url"));
			cpds.setUser(jdbcProperties.getProperty("username"));
			cpds.setPassword(jdbcProperties.getProperty("password"));
			cpds.setTestConnectionOnCheckin(true);
			cpds.setTestConnectionOnCheckout(true);
			cpds.setIdleConnectionTestPeriod(15);
			dataSource = cpds;
			
		}
		catch (Exception e){
			e.printStackTrace();
		}
	}
	
	public static DataSource getDataSource() {
		return dataSource;
	}
	
	public static Connection getConnection() throws SQLException{
		return dataSource.getConnection();
	}
	
	public static void release(Connection conn) throws SQLException {
		conn.close();
	}
	
	public static void release(Connection conn, Statement stmt, ResultSet rs) throws SQLException {
		conn.close();
		stmt.close();
		rs.close();
	}
}
